import re
from copy import deepcopy


def get_manjian_menu(data):
    shop = data.get("data")
    shopInfo = shop.get("shopInfo")

    shopName = shopInfo.get("shopName")
    deliveryFee = shopInfo.get("deliveryFee")
    minFee = shopInfo.get("minFee")
    activityList = shopInfo.get("activityList")

    discounts = list()
    new_user_reduce_fee = 0
    for activity in activityList:
        info = activity.get("actDesc")
        res = re.search(r"满\d+减\d+", info)
        res2 = re.search(r'满\d+减\d+代金券', info)
        res3 = re.search(r'配送费满减', info)
        if res and not res2 and not res3:
            for mj in info.split(";"):
                allPrice = mj.find("满")
                reducePrice = mj.find("减")
                allPrice = mj[allPrice + 1:reducePrice]
                reducePrice = mj[reducePrice + 1:]
                discounts.append((float(allPrice), float(reducePrice)))
        elif '本店新用户立减' in info:
            new_user_reduce_fee = float(re.findall(r'\d+', info)[0])



    foods = []
    discount_foods = []
    categoryList = shop.get("categoryList")
    for category in categoryList:
        for spu in category.get("spuList"):
            spuName = spu.get("spuName")
            originPrice = spu.get("originPrice")
            currentPrice = spu.get("currentPrice")
            boxFee = spu.get("skuList")[0].get("boxFee")
            sellStatus = spu.get("sellStatus")
            activityTag = spu.get("activityTag")
            if activityTag == 'discount':
                if not currentPrice == 0:
                    discount_foods.append((spuName.replace(' ', '').replace('（', '(').replace('）', ')').replace("-",
                                                                                                            "").replace(
                    "—", ""), currentPrice, boxFee))
            else:
                if not originPrice == 0:
                    foods.append((spuName.replace(' ', '').replace('（', '(').replace('）', ')').replace("-", "").replace("—",
                                                                                                                    ""),
                              originPrice, boxFee))


    for i in range(len(foods)):
        for j in range(i + 1, len(foods)):
            if foods[i][1] > foods[j][1]:
                temp = deepcopy(foods[i])
                foods[i] = deepcopy(foods[j])
                foods[j] = temp
    for i in range(len(discount_foods)):
        for j in range(i + 1, len(discount_foods)):
            if discount_foods[i][1] > discount_foods[j][1]:
                temp = deepcopy(discount_foods[i])
                discount_foods[i] = deepcopy(discount_foods[j])
                discount_foods[j] = temp

    discount_menu = []
    discounts_data = {}
    discount_menu_num = 0
    for discount_food in discount_foods:
        outOfPacket = discount_food[1] + discount_food[2] + deliveryFee - new_user_reduce_fee
        if outOfPacket >= 8 and outOfPacket <= 20:
            discount_menu.append(
                {
                    "menu" : discount_food[0] + ":" + str(discount_food[1]),
                    "packingFee" : discount_food[1],
                    "outOfPacket" : outOfPacket,
                }
                                 )
    if len(discount_menu) == 0:
        discounts_data = {"discounts" : None, "hasDiscounts" : 0, "msg" : "暂无折扣优惠方案"}
    else:
        discounts_info = {"discount_menu" : discount_menu, "minFee" : minFee, "shopName" : shopName , "new_user_reduce_fee" : new_user_reduce_fee ,"deliveryFee":deliveryFee}
        discounts_data = {"discounts" : discounts_info,"hasDiscounts" : 1, "msg" : "获取成功" }
    if len(discounts) == 0:

        return {"manjian":{"menuData": None, "hasMenu": 0, "msg": "暂无合适的优惠方案"} , "discount": discounts_data}
    allPrice = discounts[0][0]
    reduce_price = discounts[0][1]

    i = 0
    j = len(foods) - 1

    page_plan = []
    actPlan = []
    tempMethods = {"menu": []}
    tempPrice = 0
    allPackingFee = 0
    iChange = False
    jChange = False
    has_drink = False
    while i < j:
        currentIPrice = foods[i][1]
        packingIFee = foods[i][2]
        currentJPrice = foods[j][1]
        packingJFee = foods[j][2]
        if not iChange and not jChange and currentJPrice + packingJFee + tempPrice >= allPrice:
            if not isDrink(foods[j][0]):
                tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                allPackingFee += packingJFee
                tempPrice += currentJPrice
                tempPrice += packingJFee
            j -= 1
            jChange = True
            iChange = False
        elif not iChange and not jChange and currentJPrice + packingJFee + tempPrice < allPrice:
            if not isDrink(foods[j][0]):
                tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                allPackingFee += packingJFee
                tempPrice += currentJPrice
                tempPrice += packingJFee
                i += 1
                jChange = False
                iChange = True
            else:
                j -= 1
                jChange = True
                iChange = False
        elif iChange and tempPrice + currentIPrice + packingIFee >= allPrice:
            if not foods[i][0] in tempMethods["menu"]:
                if i - 1 >= 0:
                    if isDrink(foods[i][0]):
                        if has_drink:
                            i += 1
                            iChange = True
                            jChange = False
                        else:
                            has_drink = True
                            if "麻辣香锅" in shopName:
                                i += 1
                                iChange = True
                                jChange = False
                            else:

                                tempMethods["menu"].append(foods[i][0] + ":" + str(currentIPrice))
                                allPackingFee += packingIFee
                                tempPrice += currentIPrice
                                tempPrice += packingIFee
                                j -= 1
                                jChange = True
                                iChange = False
                    else:
                        tempMethods["menu"].append(foods[i][0] + ":" + str(currentIPrice))
                        allPackingFee += packingIFee
                        tempPrice += currentIPrice
                        tempPrice += packingIFee
                        j -= 1
                        jChange = True
                        iChange = False
            else:
                i += 1
                iChange = True
                jChange = False
        elif jChange and tempPrice + currentJPrice + packingJFee >= allPrice:
            if not foods[j][0] in tempMethods["menu"]:
                if j + 1 <= len(foods) - 1:
                    if abs(foods[j][1] - foods[j + 1][1]) > 0:
                        if isDrink(foods[j][0]):
                            has_drink = True
                            if not '麻辣香锅' in shopName and not len(tempMethods["menu"]) == 0:
                                has_drink = True
                                tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                                allPackingFee += packingJFee
                                tempPrice += currentJPrice
                                tempPrice += packingJFee
                        else:
                            tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                            allPackingFee += packingJFee
                            tempPrice += currentJPrice
                            tempPrice += packingJFee


                else:
                    if isDrink(foods[j][0]):
                        has_drink = True
                    if not '麻辣香锅' in shopName and not len(tempMethods["menu"]) == 0:
                        tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                        allPackingFee += packingJFee
                        tempPrice += currentJPrice
                        tempPrice += packingJFee
            j -= 1
            jChange = True
            iChange = False
        elif iChange and tempPrice + currentIPrice + packingIFee < allPrice:
            if not foods[i][0] in tempMethods["menu"]:
                if i - 1 >= 0:
                    if isDrink(foods[i][0]):
                        if has_drink:
                            i += 1
                            iChange = True
                            jChange = False
                        else:
                            has_drink = True
                            if '麻辣香锅' in shopName:
                                i += 1
                                iChange = True
                                jChange = False
                            else:

                                tempMethods["menu"].append(foods[i][0] + ":" + str(currentIPrice))
                                allPackingFee += packingIFee
                                tempPrice += currentIPrice
                                tempPrice += packingIFee
                                j -= 1
                                jChange = True
                                iChange = False
                    else:
                        tempMethods["menu"].append(foods[i][0] + ":" + str(currentIPrice))
                        allPackingFee += packingIFee
                        tempPrice += currentIPrice
                        tempPrice += packingIFee
                        i += 1
                        iChange = True
                        jChange = False
            else:
                i += 1
                iChange = True
                jChange = False
        elif jChange and tempPrice + currentJPrice + packingJFee < allPrice:
            if not foods[j][0] in tempMethods["menu"]:
                if isDrink(foods[j][0]):
                    has_drink = True
                if not '麻辣香锅' in shopName:
                    # 不希望一个方案中最贵的菜肴是酒水
                    if not len(tempMethods["menu"]) == 0:
                        tempMethods["menu"].append(foods[j][0] + ":" + str(currentJPrice))
                        allPackingFee += packingJFee
                        tempPrice += currentJPrice
                        tempPrice += packingJFee
                        i += 1
                        jChange = False
                        iChange = True
                    else:
                        j -= 1
                        jChange = True
                        iChange = False
                else:
                    i += 1
                    jChange = False
                    iChange = True
            else:
                j -= 1
                jChange = True
                iChange = False
        if tempPrice >= allPrice:
            tempMethods["all_packing_price"] = allPackingFee
            # total_price包括菜和包装费
            tempMethods["total_price"] = round(tempPrice, 1)
            out_of_pocket = tempPrice + deliveryFee - new_user_reduce_fee - reduce_price
            out_of_pocket = round(out_of_pocket , 1)
            # 过滤掉一些菜单，菜 + 包装费 大于等于 起送费；菜 + 包装费 + 配送费 < 20, 以及过滤掉全部是单点不送的菜单
            if tempPrice >= minFee and out_of_pocket >= 8 and out_of_pocket <= 20:
                fl = 0
                for fn in tempMethods.get("menu"):
                    if not ('单点' in fn or '搭配' in fn):
                        fl = 1
                    if '+' in fn or '➕' in fn:
                        fl = 0
                        break
                if fl == 1:
                    tempMethods["out_of_pocket"] = out_of_pocket
                    actPlan.append(tempMethods)
            tempMethods = {"menu": []}
            tempPrice = 0
            allPackingFee = 0
            has_drink = False

    if len(actPlan) == 0:
        return {"manjian":{"menuData": None, "hasMenu": 0, "msg": "暂无合适的优惠方案"} , "discount": discounts_data}
    for m in range(len(actPlan)):
        for n in range(m + 1, len(actPlan)):
            if actPlan[m].get("total_price") > actPlan[n].get("total_price"):
                temp = deepcopy(actPlan[m])
                actPlan[m] = deepcopy(actPlan[n])
                actPlan[n] = temp
    page_plan.append(
        {
            "actPlan": actPlan,
            "new_user_reduce_fee": new_user_reduce_fee,
            "shopName": shopName,
            "mj": "满" + str(allPrice) + "减" + str(reduce_price),
            "minFee": minFee,
            "deliveryFee": deliveryFee,
        }
    )

    return {"manjian":{"menuData": page_plan, "hasMenu": 1, "msg": "获取成功"} , "discount": discounts_data}

def isDrink(food_name):
    drinks = ["可乐", "芬达", "雪花啤酒", "雪碧", "冰糖雪梨", "牛栏山", "二锅头", "体质能量", "青梅绿茶",
              "冰红茶", "柚子茶", "王老吉", "酸梅汤", "勇闯天涯", "娃哈哈", "矿泉水", "农夫山泉", "汽水", "营养快线", "郎歪", "歪嘴", "郎酒",
              "脉动", "北冰洋", "冰露", "今麦郎", "橙汁", "晶莹葡萄", "美年达", "百岁山", "怡宝", "冰糖雪梨", "纯悦", "茉莉蜜茶", "大白梨", "雀巢", "六个核桃",
              "纯生", "水蜜桃", "果粒橙", "酸酸乳", "开卫", "红茶", "阿萨姆", "蜂蜜柚子", "绿茶", "AD钙", "润田", "乳酸菌", "山楂树下", "天涯", "蓝莓",
              "夺命大乌",
              "加多宝", "凉茶", "名仁", "苏打水", "劲酒", "露露", "江小白", "雪花", "烧酒", "红牛", "完达山", "一担粮", "百威", "椰子", "牛奶", "燕京",
              "宏宝莱", "茶Π", "水溶"]
    for drink_name in drinks:
        if drink_name in food_name:
            if '+' in food_name:
                return False
            else:
                return True
    return False

